//
// Created by liwen on 2023/12/15.
//

#include "event_group.h"
#include <iostream>

Defer::Defer(DeferCB cb) {
    cb_ = cb;
}

Defer::~Defer() {
    if(cb_){
        cb_();
    }
}

std::shared_ptr<EventGroup> EventGroup::createEventGroup(){
    std::shared_ptr<EventGroup> eventGroup;
    eventGroup.reset(new EventGroup());
    return eventGroup;
}

EventGroup::EventGroup() {
    promise_ = std::make_shared<std::promise<void>>();
}

EventGroup::~EventGroup(){

}

void EventGroup::signalOne(){
    std::thread::id current_thread_id = std::this_thread::get_id();
    int count = count_.fetch_sub(1);
    printf("id:%d count:%d \n", current_thread_id, count);
    if(count == 1){
        promise_->set_value();
        printf("id:%d signal \n", current_thread_id);
    }
}

void EventGroup::init(int count) {
    count_.store(count);
}

void EventGroup::waitAll() {
    if(promise_){
        promise_->get_future().wait();
    }
}
